package com.keson.door2.util;

import android.content.Context;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Locale;

public class TTSUtil {
    private static TextToSpeech textToSpeech;
    private static HashMap ttsOptions = new HashMap<>();

    public static void init(Context context){
        TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.CHINESE);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.i("TTS","加载失败，缺少语音数据，或语言不支持，请安装讯飞语音+");
                    }else{
                        Log.i("TTS","加载成功");
                    }

                }
            }
        };
        textToSpeech = new TextToSpeech(context, onInitListener);
        textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
//            Handler handler = MainActivity.getVideoVolHandler();
            @Override
            public void onStart(String s) {
//                handler.sendMessage(handler.obtainMessage(100, "pause"));
            }

            @Override
            public void onDone(String s) {
//                handler.sendMessage(handler.obtainMessage(100, "play"));
            }

            @Override
            public void onError(String s) {

            }
        });

        //utterance，这个参数随便写，用于监听播报完成的回调中
        ttsOptions.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utterance");
    }

    public static void speek(String text){
        if(ismServiceConnectionUsable(textToSpeech)){
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, ttsOptions);
        }
    }

    /**
     * TTS初始化之后有时会无法播放语音。
     * 从打印日志看failed: not bound to TTS engine
     * 找到源代码打印处
     * if (mServiceConnection == null) {
     *      Log.w(TAG, method + " failed: not bound to TTS engine");
     *   return errorResult;
     *  }
     *  通过反射判断mServiceConnection是否为空
     * @param tts
     * @return true 可用
     */
    public static boolean ismServiceConnectionUsable(TextToSpeech tts) {

        boolean isBindConnection = true;
        if (tts == null){
            return false;
        }
        Field[] fields = tts.getClass().getDeclaredFields();
        for (int j = 0; j < fields.length; j++) {
            fields[j].setAccessible(true);
            if (TextUtils.equals("mServiceConnection",fields[j].getName()) && TextUtils.equals("android.speech.tts.TextToSpeech$Connection",fields[j].getType().getName())) {
                try {
                    if(fields[j].get(tts) == null){
                        isBindConnection = false;
                        Log.i("TTS","*******反射判断 TTS -> mServiceConnection == null*******" );
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return isBindConnection;
    }
}
